<?php

define("TOKEN", "CF235036C653C953A77797AC07F52BEC");
class WeixinAction extends Action{
	
	
	public $keyword = "";
	public $fromUsername = "";
	public $toUsername = "";
	public $time = "";
	public $Event = "";
	
	function interfaces(){
// 		$this->valid();
		$this->checkReceive();
		
		if($this->Event == 'subscribe'){
			$this->TextMsg("欢迎来到橙果实验室，回复【你好】获得更多信息。");
		}else{
			
			if($this->keyword=='你好'){
				$this->TextMsg("1、授权\r\n2、没有了");
			}elseif($this->keyword=='授权'){
				$this->TextMsg("<a href='http://olab.hjie.net/Auth/A1'>点击授权</a>");
			}
			
		}
		
	}
	
	
	function checkReceive(){
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		
		//extract post data
		if (!empty($postStr)){
			/* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
			 the best way is to check the validity of xml by yourself */
			libxml_disable_entity_loader(true);
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$this->fromUsername = $postObj->FromUserName;
			$this->toUsername = $postObj->ToUserName;
			$this->keyword = trim($postObj->Content);
			$this->Event = trim($postObj->Event);
			$this->time = time();
			
		}else {
			echo "";
			exit;
		}
	}
	
// 	<xml>
// 	<ToUserName><![CDATA[toUser]]></ToUserName>
// 	<FromUserName><![CDATA[FromUser]]></FromUserName>
// 	<CreateTime>123456789</CreateTime>
// 	<MsgType><![CDATA[event]]></MsgType>
// 	<Event><![CDATA[subscribe]]></Event>
// 	</xml>
	
	public function TextMsg($contentStr){
		
		$msgType = "text";
		
		$textTpl = "<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%s</CreateTime>
			<MsgType><![CDATA[%s]]></MsgType>
			<Content><![CDATA[%s]]></Content>
			<FuncFlag>0</FuncFlag>
			</xml>";
		
// 		$contentStr = "<a href='http://www.baidu.com/'>Welcome to wechat world!</a> fromUser:" . $fromUsername .". ToUser:".$toUsername;
		$resultStr = sprintf($textTpl, $this->fromUsername, 
				$this->toUsername, $this->time, $msgType, $contentStr);
		echo $resultStr;
		exit();
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function valid()
	{
		$echoStr = $_GET["echostr"];
	
		//valid signature , option
		if($this->checkSignature()){
			echo $echoStr;
			exit;
		}
	}
	private function checkSignature()
	{
		// you must define TOKEN by yourself
		if (!defined("TOKEN")) {
			throw new Exception('TOKEN is not defined!');
		}
	
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];
	
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		// use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
	
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}